package com.ruifight.data.controller;

import com.ruifight.data.bean.*;
import com.ruifight.data.common.BaseController;
import com.ruifight.data.common.HexadecimalConversion;
import com.ruifight.data.common.HttpRequest;
import com.ruifight.data.service.IDataServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

/**
 * Created by liuhx on 2016/11/23.
 */
@Controller
public class RequestController{
    private static final Logger logger = LoggerFactory.getLogger(RequestController.class);
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    IDataServer dataServer;
    static Socket s = null;
    static DataOutputStream dout = null;
    static DataInputStream din = null;
    static String backCMD = null;
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;
//		response.setContentType("text/json");
//		response.setCharacterEncoding("GBK");
    }
    public IDataServer getDataServer() {
        return dataServer;
    }
    @Autowired
    public void setDataServer(IDataServer dataServer) {
        this.dataServer = dataServer;
    }

    @RequestMapping("gateway")
    @ResponseBody
    public void DataRequest()
    {
      int message=0;
        try {
        Map<String, String[]> params = request.getParameterMap();
        String queryString="";
        for (String key : params.keySet()) {
            String[] values = params.get(key);
                String value = values[0];
                queryString += key  + value ;
        }
        logger.info("数据"+queryString);
        byte[] bytes =  queryString.getBytes("ISO-8859-1");
        String data=HexadecimalConversion.toHex(bytes);
        //与头部分离
//        String a[] = data.split("0D 0A 0D 0A ");
//        String topa=a[0].replace(" ","");
//        String top = HexadecimalConversion.toStringHex(topa);//头部
//        System.out.println(top);
        //去掉空格去除空值
        logger.info("全数据"+data);
        String b[] = data.split(" ");
        StringBuffer sb = new StringBuffer();
        //分数据分开为协议头 固定部分 可变部分
        for(int i=0; i<b.length; i++) {
            if("".equals(b[i])) {
                continue;
            }
            sb.append(b[i]);
            if(i != b.length - 1) {
                sb.append(";");
            }
        }
        b = sb.toString().split(";");
        String head[]= new String[1];
        String body[]= new String[14];
            System.out.println("b的长度为："+b[0]);
            System.out.println("b的长度为："+b.length);
        String other[]= new String[b.length-15];
        for(int s=0;s<b.length;s++)
        {
            if(s==0)
            {
                head[0]=b[0];
            }else if(s>0&&s<15)
            {
                body[s-1]=b[s];
            }else
            {
                other[s-15]=b[s];
            }
        }
        RawDataBean rawDataBean = new RawDataBean();
        /**
         * 头部解析
         */
            String arrString = Arrays.toString(head);
            logger.info("头部数据"+arrString);
        String sda = HexadecimalConversion.HexToBinary(head[0]);
        rawDataBean.setHeadDataEdition(sda.substring(0, 3));
        rawDataBean.setHeadDataType(sda.substring(3, 6));
        rawDataBean.setHeadDataSpare(sda.substring(6,8));
        logger.info("版本号:"+rawDataBean.getHeadDataEdition()+"协议类型:"+rawDataBean.getHeadDataType()+"备用:"+rawDataBean.getHeadDataSpare());
            System.out.println("头部转化后"+sda);
        /**
         * 固定部分解析 --单独一个进程
         */
        String bodyDataString = HexadecimalConversion.dataDecrypt(body);//解密
        String bodyDataCpuId=bodyDataString.substring(0, 24); //cpuid 12B
        String bodyDataResidualElectric=bodyDataString.substring(24,26);//电量 1B
        String sav=HexadecimalConversion.HexToBinary(bodyDataString.substring(27));
        String bodyDataPowerSupply=sav.substring(0);//供电方式 0=电源,1=电池 1bit
        String bodyDataSpare=sav.substring(1, 8);//备用 7bit 总为0
        rawDataBean.setBodyDataCpuId(bodyDataCpuId);
        rawDataBean.setBodyDataResidualElectric(bodyDataResidualElectric);
        rawDataBean.setBodyDataPowerSupply(bodyDataPowerSupply);
        rawDataBean.setBodyDataSpare(bodyDataSpare);
        logger.info("cpuid="+bodyDataCpuId+"电量:"+bodyDataResidualElectric+"备用:"+bodyDataSpare);
        /**
         * 可变部分解析
         */
        String otherDataString = HexadecimalConversion.dataDecrypt(other);//解密
            logger.info("获取数据"+rawDataBean.getHeadDataType());
        int type = Integer.parseInt(rawDataBean.getHeadDataType(),2);
            logger.info("type:"+type);
            if(type==0)//数据-检测
        {
            TestDataBean testDataBean = new TestDataBean();
            testDataBean.setTestDataLength(otherDataString.substring(0,4));//总长度
            int length = Integer.parseInt(otherDataString.substring(4,6),16);//数据个数
            testDataBean.setTestDataFieldNum(length);
            String bianmaliebiao = otherDataString.substring(6,6+2*length);//编码列表
            testDataBean.setTestDataCodeList(HexadecimalConversion.hexToDecimalInt(bianmaliebiao));
            //获得每个字段长度
            int codeLength[] = TestDataCode.findlenth(testDataBean.getTestDataCodeList());
            //数据条数
            int tiaoshu = Integer.parseInt(otherDataString.substring(6+2*length,6+2*length+2));
            testDataBean.setTestDataNum(tiaoshu);
            for (int code:codeLength)
            {
                System.out.print("code"+code);
            }
            //数据
            String shuju = otherDataString.substring(6+2*length+2,otherDataString.length());
            int num =shuju.length()/tiaoshu;
            int dataMapper[][]  = new int[tiaoshu][length];
            for(int z=0;z<tiaoshu;z++)
            {
                int h=14;
                String shujudata = shuju.substring(z*num,(z+1)*num);
                String biaozhi=shujudata.substring(0,2);
                System.out.print("数据标志"+biaozhi);
                String meitiaoshijian = shujudata.substring(2,14);
                System.out.print("时间"+meitiaoshijian);
                for(int k=0;k<length;k++)
                {
                    int jhg= Integer.parseInt(shujudata.substring(h,h + (codeLength[k]*2)),16);
                    dataMapper[z][k]=jhg;
                    System.out.println("数字:"+jhg);
                    h = h + codeLength[k]*2;
                }
            }
            for(int o=0;o<codeLength.length;o++)
            {
                System.out.print(testDataBean.getTestDataCodeList()[o]+" ");
            }
            for (int f=0;f<dataMapper.length;f++)
            {
                for(int u=0;u<dataMapper[f].length;u++)
                {
                    System.out.print(dataMapper[f][u]+"  ");
                }
                System.out.println("");
            }
            // 此处进行数据的insert 每个单独线程
        }else if(type ==1)//数据：事件通知
        {
            System.out.println("数据"+otherDataString);
            String time = HexadecimalConversion.hexToDecimal(otherDataString.substring(0,12));
            int eventType = Integer.parseInt(otherDataString.substring(12,14),16);
            int eventContent = Integer.parseInt(otherDataString.substring(14,16),16);
            String eventParm = HexadecimalConversion.hexToDecimal(otherDataString.substring(16,20));
            System.out.println("time"+time+"eventType"+eventType+"eventContent"+eventContent+"eventParm"+eventParm);
            System.out.print("事件通知");
            if(eventType==0)
            {
                System.out.print("系统");
                if(eventContent==0)
                {
                    System.out.print("启动-正常上电");
                }
                if(eventContent==1)
                {
                    System.out.print("启动-平台命令");
                }
                if(eventContent==2)
                {
                    System.out.print("启动-设备故障");
                }
                else
                {
                    System.out.print("启动-平台命令");
                }
            }
            if(eventType==1)
            {
                System.out.print("GPRS-信号异常");
            }
            if(eventType==2)
            {
                System.out.print("存储失败");
            }
            if(eventType==3)
            {
                System.out.print("电池-");
                if(eventContent==0)
                {
                    System.out.print("电池故障");
                }else {
                    System.out.print("低电压警告");
                }
            }
            if(eventType==4)
            {
                System.out.print("命令响应更改网关地址");
            }
            if(eventType==5)
            {
                System.out.print("传感器1-读取数据失败");
            }
            if(eventType==6)
            {
                System.out.print("传感器2-");
                if(eventContent==0)
                {
                    System.out.print("读取数据失败");
                }else {
                    System.out.print("传感器故障");
                }
            }
            // 此处进行数据的insert 每个单独线程
        }else if(type ==2)//数据：设备配置
        {
            System.out.print("设备配置");
            String paramLength=otherDataString.substring(0,4);
            System.out.print("paramLength"+paramLength);
            String paramData=otherDataString.substring(4,otherDataString.length());
           // String paramDatas=HexadecimalConversion.toStringHex(paramData);
            String daTaString="";
            int lk =0;
            for(int i=0;i<paramData.length()/2;i++){
                String pra = paramData.substring(lk,lk+2);
                if(paramData.substring(lk,lk+2).equals("09")){
                 pra="3B";
                }
                daTaString = daTaString +pra;
                lk=lk+2;
            }

            String paramDatas=HexadecimalConversion.toStringHex(daTaString);
            String parm[]=paramDatas.split("=|;");
//            for(int i=0;i<parm.length;i++)
//            {
//                System.out.println(parm[i]);
//            }
            ParamDataBean.returnParam(parm);
            logger.info("daTaString为"+daTaString);
            logger.info("paramDatas为"+paramDatas);
            logger.info("otherDataString"+otherDataString);
           System.out.print("paramData"+paramData);
            // 此处进行数据的insert 每个单独线程
        }else if(type ==3)//命令：获取下发数据
        {
            System.out.println("3");
        }else if(type ==4)//命令：获取校准时间
        {
            System.out.println("4");
        }else if(type ==5)//命令：获取校准时间
            {
                System.out.println("回传配置设置");
            }
            else if(type ==6)//命令：获取校准时间
            {
                System.out.println("回传事件通知");
            }
//String test="50 4F 53 54 20 2F 67 61 74 65 77 61 79 2F 20 48 54 54 50 2F 31 2E 31 0D 0A 43 6F 6E 74 65 6E 74 2D 54 79 70 65 3A 20 61 70 70 6C 69 63 61 74 69 6F 6E 2F 78 2D 77 77 77 2D 66 6F 72 6D 2D 75 72 6C 65 6E 63 6F 64 65 64 0D 0A 48 6F 73 74 3A 20 31 31 35 2E 32 38 2E 32 31 33 2E 31 33 37 3A 38 30 38 30 0D 0A 43 6F 6E 74 65 6E 74 2D 4C 65 6E 67 74 68 3A 20 30 31 30 39 0D 0A 0D 0A 00 46 70 65 64 66 66 66 66 66 66 66 06 02 66 65 B8 6D 66 67 64 65 62 63 B6 B7 B4 B5 B0 64 66 76 6A 6B 77 6E 67 66 1B 67 62 66 66 66 CB 66 66 67 35 67 C8 66 CA 66 6D 66 57 66 66 66 66 66 66 66 76 6A 6B 77 6E 66 66 30 67 62 66 66 66 CB 66 66 67 35 67 C8 66 CA 66 6D 66 57 66 66 66 66 66 66";
        /**
         * 向服务器发送数据  开启一个新线程 如果没返回值则重新发送直到有返回值为止
         */
       //String re = HttpRequest.sendPost("http://123.56.11.105:15006/gateway",test);

          /*
           *   TCP
           */
            StringBuffer z=new StringBuffer();
            for(int i=0;i<125;i++){

                z.append("a");

            }
            int len = z.length();//输出7
            logger.info("长度为"+len);
            StringBuffer stringBuffer=new StringBuffer(data);
            stringBuffer.insert(0,z);
            data= stringBuffer.toString();
            //logger.info("queryString为"+queryString);
            Socket s=new Socket("123.56.11.105",15006);//创建TCP链接
            OutputStream os=s.getOutputStream();
            os.write(data.getBytes());
            s.shutdownOutput();
            s.close();


//            Socket  s = new Socket("123.56.11.105",15006);
//           PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
//            pw.println("queryString为"+queryString);
//            pw.close();
//            s.close();
            // System.out.println("返回"+re);
        // 去掉最后一个空格
//        Timestamp d = new Timestamp(System.currentTimeMillis());
//        DataBean dataBean = new DataBean();
//        dataBean.setDeviceDate(d);
//        dataBean.setDeviceData(queryString);
//        dataServer.insert(dataBean);
//        logger.info("POST " + request.getRequestURL() + " " + queryString);
            message=0x00;
        //  logger.info("message"+0x00);

            response.getWriter().write(message);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    static public void sendCMD(final String cmd) {
        try {
            if (s == null)
                s = new Socket("123.56.11.105", 15006);
            if (dout == null)
                dout = new DataOutputStream(s.getOutputStream());
            if (din == null)
                din = new DataInputStream(s.getInputStream());
            Thread.sleep(50, 0); // 实际中刚连上后发数据需要一定延时 确保双方链接初始化完成

            char[] temp = new char[4];
            for (int i = 0; i < cmd.length(); ++i) {
                temp[i] = (char) (cmd.charAt(i) - '0');
            }
            String strTemp = new String(temp);
            dout.writeBytes(strTemp);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

